package com.example.fbi_text.Acitivity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.fbi_text.R;
import com.example.fbi_text.adapter.CartAdapter;
import com.example.fbi_text.bean.ProductCart;
import com.example.fbi_text.database.DBHelper;

import java.util.List;

public class CartActivity extends AppCompatActivity {
    private RecyclerView recyclerView;
    private CartAdapter cartAdapter;
    private DBHelper dbHelper;
    private Button checkoutButton;
    private TextView totalPriceText;

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cart);

        dbHelper = DBHelper.getInstance(this);
        recyclerView = findViewById(R.id.cart_recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        totalPriceText = findViewById(R.id.total_price_text);
        checkoutButton = findViewById(R.id.checkout_button);
        checkoutButton.setOnClickListener(v -> showCheckoutSuccess());
        loadCartItems();
    }

    private void loadCartItems() {
        List<ProductCart> cartItems = dbHelper.getAllCartItems();
        cartAdapter = new CartAdapter(this, cartItems, totalPriceText, dbHelper);
        recyclerView.setAdapter(cartAdapter);
    }

    private void showCheckoutSuccess() {
        if (cartAdapter != null) {
            Toast.makeText(this, "结算成功，总金额：¥" + cartAdapter.getTotalCost(), Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(this, "购物车适配器未找到，请检查代码", Toast.LENGTH_LONG).show();
        }
    }
}